package com.lmq.Utils

import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession

/** Lazily instantiated singleton instance of SparkSession */
object SparkSessionSingleton {

  @transient  private var instance: SparkSession = _

  def getInstance(sparkConf: SparkConf): SparkSession = {
    /**
     * if sparkConf is null,
     * the default appName is singletonSC, and default master is
     * local[*] for convenience.
     */
    if (instance == null) {
      if (sparkConf != null)
        instance = SparkSession
          .builder
          .config(sparkConf)
          .getOrCreate()
      else
        instance = SparkSession
          .builder
          .config(new SparkConf().setAppName("singletonSC").setMaster("local[*]"))
          .getOrCreate()
    }
    instance
  }

  def getInstanceWithSync(sparkConf: SparkConf): SparkSession = {
    if (instance == null) {
      synchronized {
        if (sparkConf != null)
          instance = SparkSession
            .builder
            .config(sparkConf)
            .getOrCreate()
        else
          instance = SparkSession
            .builder
            .config(new SparkConf().setAppName("singletonSC").setMaster("local[*]"))
            .getOrCreate()
      }
    }
    instance
  }
}
